package cn.green.captcha.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 图形验证码服务Controller
 */
@Controller
public class CaptchaController {

    @Autowired
    private Producer producer;

    /**
     * 获取图形验证码
     * @param request           请求
     * @param response          响应
     * @throws IOException      io异常
     */
    @GetMapping("/captcha.jpg")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置响应内容类型为image/jpeg图片格式
        response.setContentType("image/jpeg");
        //创建验证码文本
        String text = producer.createText();
        //向会话中设置图形验证码的文本
        request.getSession().setAttribute("captcha", text);
        //根据验证码文本制造一个图片
        BufferedImage image = producer.createImage(text);
        //获取响应中的输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //写出图片流
        ImageIO.write(image, "jpg", outputStream);
        try{
            outputStream.flush();
        } finally {
            outputStream.close();
        }
    }

}
